package com.karry.yl.web.baseinfo;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.karry.commons.base.SuperController;
import com.karry.commons.util.TimeUtil;
import com.karry.commons.vo.LayTableResponse;
import com.karry.yl.domain.elder.Searchrecord;
import com.karry.yl.service.baseinfo.SearchrecordService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;


/**
 * @author Administrator
 */
@Controller
@RequestMapping("/searchrecord")
public class SearchrecordController extends SuperController {

    @Autowired
    private SearchrecordService searchrecordService;

    @RequestMapping
    public String listUI(){
        return "elder/searchrecord/list";
    }

    @RequestMapping("/add")
    public String addUI(){
        return "elder/searchrecord/add";
    }

    @RequestMapping("edit")
    public String editUI(Long id, ModelMap map){
        Searchrecord searchrecord = searchrecordService.selectById(id);
        map.put("searchrecord",searchrecord);
        return "elder/searchrecord/edit";
    }

    @RequestMapping("/list")
    @ResponseBody
    public LayTableResponse listUI(int page, int limit){
        Page<Searchrecord> listPage = searchrecordService.selectPage(new Page<Searchrecord>(page, limit),new EntityWrapper<Searchrecord>().eq("orgId",currentUser.getOrgId()).eq("deleted",false).orderBy("createdTime",false));
        return new LayTableResponse(listPage.getRecords(),listPage.getTotal());
    }

    @RequestMapping("/save")
    public String save(Searchrecord searchrecord){
        searchrecord.setOrgId(currentUser.getOrgId());
        searchrecordService.insert(searchrecord);
        return "redirect:/searchrecord";
    }

    @RequestMapping("/update")
    public String update(Searchrecord searchrecord){
        searchrecord.setOrgId(currentUser.getOrgId());
        searchrecordService.updateById(searchrecord);
        return "redirect:/searchrecord";
    }

    /**
     * 删除
     * @param
     * @return
     */
    @RequestMapping(path = "/delete")
    public String delete(@RequestParam("id") List<Long> ids){
        searchrecordService.deleteBatchIds(ids);
        return "redirect:/searchrecord";
    }


    /**
     * 老人档案导出为excel
     *
     * @param response
     * @throws Exception
     */
    @RequestMapping("/export/excel")
    public void exportExcel(HttpServletResponse response) {
        //查询所有的巡检记录
        List<Searchrecord> searchrecords = searchrecordService.selectList(new EntityWrapper<Searchrecord>().eq("orgId", currentUser.getOrgId()));
        //生成Excel,并存储临时文件
        // 创建一个HSSFWorkbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 在workbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("咨询记录");

        // 表头
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式

        //声明列对象
        HSSFCell cell = null;

        //创建标题
        String[] title = {"客户姓名", "联系电话", "咨询事项 "};
        for (int i = 0; i < title.length; i++) {
            row.setHeightInPoints(20);
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
            sheet.setColumnWidth(i, 21 * 256);
        }

        //创建内容
        for (int i = 0; i < searchrecords.size(); i++) {
            row = sheet.createRow(i + 1);
            row.setHeightInPoints(20);
            Searchrecord searchrecord = searchrecords.get(i);
            row.createCell(0).setCellValue(searchrecord.getName());
            row.createCell(1).setCellValue(searchrecord.getPhone());
            row.createCell(2).setCellValue(searchrecord.getRemark());

        }

        //下载
        response.setCharacterEncoding("UTF-8");
        try (ServletOutputStream out = response.getOutputStream();) {
            response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode("咨询信息-" + TimeUtil.format(new Date(), "yyyyMMddHHmmss") + ".xls", "UTF-8"));
            wb.write(out);
        } catch (IOException e) {
            //TODO 下载失败日志记录
        } finally {
            try {
                wb.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
